package com.project.servlet;

import com.github.pagehelper.PageInfo;
import com.project.bean.ProductBean;
import com.project.service.IProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@Controller
public class CutServlet extends HttpServlet {
    @Autowired
    private IProductService service;
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        //得到客户端提交的页码
        String pageNum = req.getParameter("pageNO");
        //默认显示第一页
        if(pageNum == null){
            pageNum = "1";
        }
        //得到页码
        int pageNO = Integer.parseInt(pageNum);
        //调用业务方法
        PageInfo<ProductBean> pageInfo = service.cutAll(pageNO);
        //得到当前页需要显示的数据
        List<ProductBean> productList = pageInfo.getList();

        String info = "<table border='1' width='50%'>";
        info += "<thead><tr><th>编号</th><th>商品名</th><th>价格</th><th>类别</th></tr></thead>";

        info += "<tbody>";
        for(ProductBean product : productList){
            info += "<tr><td>"+product.getId()+"</td><td>"+product.getName()+"</td>" +
                    "<td>"+product.getPrice()+"</td><td>"+product.getType()+"</td></tr>";
        }

        info += "</tbody></table>";

        for(int i=1;i<pageInfo.getPages();i++){
            info += "<a href='/cutAll?pageNO="+i+"' style='margin-left:10px'>"+i+"</a>";
        }

        resp.getWriter().print(info);
    }
}
